import request from "@/axios"
import { ResponseData } from "../../../../constants"
import { saveUser } from "./type"
import { menuApi } from "../menu"
import { builderMenuTree } from "@/utils"
import { ElMessage } from "element-plus"

enum Api {
  userList = "/user/list",
  saveUser = "/user/save",
  updateUser = "/user/update",
  // updateUserRole = "/user/update-user-role",
  removeUser = "/user/remove",
  batchRemoveUser = "/user/remove-batch",
  getUserMenu = "/user/menus",
  getUserRoles = "/user/role_permission",
}

export const userApi = {
  getUserMenuApi: async () => {
    // 获取用户菜单
    const userMenuRes = await request.get<ResponseData>(Api.getUserMenu)
    // console.log(userMenuRes);
    // 获取所有菜单
    const allMenusRes = await menuApi.queryAllMenusApi()
    if (userMenuRes.code !== 200 || allMenusRes.code !== 200) {
      ElMessage.error(userMenuRes.data.msg)
      console.error(userMenuRes.data.msg);
      throw new Error("获取用户菜单失败")
    }
    // 生成菜单树
    return builderMenuTree(userMenuRes.data, allMenusRes.data)
  },
  getUserApi: (params: any) => {
    return request.get<ResponseData>(Api.userList, params)
  },
  getUserRolesApi: () => {
    return request.get<ResponseData>(Api.getUserRoles, {})
  },
  saveUser: (params: saveUser) => {
    return request.post<ResponseData>(Api.saveUser, params)
  },
  updateUser: (params: saveUser) => {
    return request.post<ResponseData>(Api.updateUser, params)
  },
  // updateUserRole: (params: any) => {
  //   return request.post<ResponseData>(Api.updateUserRole, params)
  // },
  removeUser: (userId: string) => {
    return request.get<ResponseData>(Api.removeUser, { id: userId })
  },
  batchRemoveUser: (ids: string[]) => {
    return request.post<ResponseData>(Api.batchRemoveUser, { ids })
  }
}